package com.zbkj.crmeb.store.service.impl;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.zbkj.crmeb.store.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.constants.Constants;
import com.zbkj.crmeb.express.model.Express;
import com.zbkj.crmeb.express.service.ExpressService;
import com.zbkj.crmeb.store.model.OrderInfoDelivery;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.model.StoreOrderInfo;
import com.zbkj.crmeb.store.request.StoreOrderSendRequest;

import lombok.extern.slf4j.Slf4j;

/**
 * 凯仓物流信息查询
 * @author daigb
 * @date:  2023-01-04 10:54
 */
@Slf4j
@Service("kaiCangTradeServiceImpl")
public class KaiCangTradeServiceImpl implements CommonTradeService {
    @Autowired
    StoreOrderService storeOrderService;
    @Autowired
    StoreOrderInfoService storeOrderInfoService;
    @Autowired
    PurchaseGoodsService purchaseGoodsService;
    @Autowired
    OrderInfoDeliveryService orderInfoDeliveryService;
    @Autowired
	@Qualifier(value = "kaiCangStoreOrderServiceImpl")
    CommonStoreOrderService kaiCangStoreOrderService;
    @Autowired
    ExpressService expressService;

    private static Map<String, Integer> expressMap = new HashMap<>();
    static {
    	expressMap.put("YTO", 243);
    	expressMap.put("YUNDA", 286);
    	expressMap.put("ZTO", 429);
    	expressMap.put("SF", 188);
    	expressMap.put("YOUZHENG", 31);
    	expressMap.put("default", 31);
    }
    
	@Override
	public void tradeFullinfoget() {
		// 查询所有未收货的凯仓订单
		List<StoreOrderInfo> infos = storeOrderInfoService.list(Wrappers.<StoreOrderInfo>lambdaQuery()
				.in(StoreOrderInfo :: getStatus, Arrays.asList(-3, -1, 1, 2, 6))
				.in(StoreOrderInfo :: getIsWzbsc, true)
				);
		if(CollectionUtils.isEmpty(infos)) {
			log.info("--------------- 查询凯仓订单物流信息, 无可查订单 ---------------");
			return;
		}
		List<Integer> orderIds = infos.stream().map(StoreOrderInfo::getOrderId).collect(Collectors.toList());
		// 查询所有未收货的订单
		List<StoreOrder> orders = storeOrderService.list(Wrappers.<StoreOrder>lambdaQuery()
				.in(StoreOrder :: getStatus, Arrays.asList(-3, -1, 1, 2, 6))
				.in(StoreOrder :: getId, orderIds)
				);
		
		log.info("--------------- 查询凯仓订单物流信息, 总数据: {} ---------------", infos.size());
		for(StoreOrder order : orders) {
			log.info("--------------- 开始查询订单: {} 物流信息 ---------------", order.getOrderId());
			getTrade(order);
		}
		log.info("--------------- 查询凯仓商品订单物流信息结束 ---------------");
	}
	
	/**
	 * 物流查询
	 * @author daigb
	 * @date:  2023-01-04 11:16
	 */
	private void getTrade(StoreOrder order) {
		try {
			JSONObject result = kaiCangStoreOrderService.queryOrder(order.getOrderId());
			if(null == result) {
				log.info("--------------- 查询凯仓商品订单物流信息失败或者无物流, 订单号: {} ---------------", order.getOrderId());
				return;
			}
			// 只处理订单清关放行的订单
			String systemRemark = result.getString("systemRemark");
			List<String> statusList = Arrays.asList("清关完成", "下发仓库", "已打单", "订单出库", "揽收", "签收");
			String orderInfoStatusDesc = result.getString("orderInfoStatusDesc");
			if (StringUtils.isBlank(orderInfoStatusDesc)||!statusList.contains(orderInfoStatusDesc)){
				log.info("{}:订单未放行，凯仓状态：{},{}",order.getOrderId(),orderInfoStatusDesc,systemRemark);
				return;
			}

			// 需要更新物流的子订单
			List<StoreOrderInfo> infos = storeOrderInfoService.list(Wrappers.<StoreOrderInfo>lambdaQuery()
					.eq(StoreOrderInfo :: getOrderId, order.getId())
					);
			// 对应物流
    		String postId = result.getString("expressNo"); // 快递单号
    		String logisticName = result.getString("expressId").toUpperCase(); // 快递简称
    		for(StoreOrderInfo info : infos) {
    			// 查询系统物流单号
    			if(StringUtils.isNotBlank(postId)) {
    				int deliveryCount = orderInfoDeliveryService.count(Wrappers.<OrderInfoDelivery>lambdaQuery()
    						.eq(OrderInfoDelivery :: getOrderInfoId, info.getId())
    						.eq(OrderInfoDelivery :: getDeliveryNumber, postId)
    						);
    				// 不存在则新增
    				if(0 >= deliveryCount) {
    					int expressId = null == expressMap.get(logisticName) ? expressMap.get("default") : expressMap.get(logisticName);
    					// 判断订单状态(代发货和待确认)
    					if(Constants.ORDER_STATUS_H5_NOT_SHIPPED == info.getStatus() || Constants.ORDER_STATUS_H5_CONFIRM == info.getStatus()) {
    						StoreOrderSendRequest request = new StoreOrderSendRequest();
    						request.setType("1");
    						request.setLogisticsType(0);
    						request.setExpressId(expressId + "");
    						request.setExpressCode(postId);
    						request.setId(info.getOrderId());
    						request.setOrderInfoId(info.getId());
    						request.setName("物流快递");
    						request.setLevel(1);
    						request.setChannel(4);
    						request.setIsConfirm(true);
    						
    						storeOrderService.send(request);
    					} else {
    						Express express = expressService.info(expressId);
    						OrderInfoDelivery orderInfoDelivery = new OrderInfoDelivery();
    						orderInfoDelivery.setOrderInfoId(info.getId());
    						orderInfoDelivery.setExpressId(express.getId());
    						orderInfoDelivery.setDeliveryCode(express.getCode());
    						orderInfoDelivery.setDeliveryCompany(express.getName());
    						orderInfoDelivery.setDeliveryNumber(postId);
    						orderInfoDelivery.setName("物流快递");
    						orderInfoDelivery.setChannel(4);
    						orderInfoDeliveryService.save(orderInfoDelivery);
    					}
    				} else {
    					log.info("--------------- 查询凯仓商品订单物流信息, 订单号: {}, 该订单物流已录入, 无需再次记录 ---------------", order.getOrderId());
    				}
    			}
    		}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
    
}
